package cn.icare.cms.impl;

import cn.icare.cms.ItemService;
import cn.icare.cms.ListUtil;
import cn.icare.cms.StringUtil;
import cn.icare.cms.dao.mapper.CustomMapper;
import cn.icare.cms.dao.mapper.ItemCatMapper;
import cn.icare.cms.dao.mapper.ItemMapper;
import cn.icare.cms.dao.mapper.ItemPicMapper;
import cn.icare.cms.dao.po.Item;
import cn.icare.cms.dao.po.ItemCat;
import cn.icare.cms.dao.po.ItemPic;
import cn.icare.cms.model.enums.CommonStatusEnum;
import cn.icare.cms.model.enums.ItemStatusEnum;
import cn.icare.cms.model.ro.AddItemRO;
import cn.icare.cms.model.ro.EditItemRO;
import cn.icare.cms.model.ro.ItemDetailVO;
import cn.icare.cms.model.vo.rest.ItemPicVo;
import cn.icare.cms.model.vo.rest.ItemVO;
import cn.icare.cms.model.vo.rest.MsgDatasVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Stream;

@Service
public class ItemServiceImpl implements ItemService {

    @Resource
    private ItemMapper itemMapper;
    @Resource
    private ItemPicMapper itemPicMapper;

    @Resource
    private CustomMapper customMapper;

    @Resource
    private ItemCatMapper itemCatMapper;

    private final Logger logger = LoggerFactory.getLogger(ItemServiceImpl.class);

    @Override
    public Long createOne(AddItemRO ro, String actionUserName) {
        Item item = new Item();
        item.setCode(ro.getCode());
        item.setTitle(ro.getTitle());
        item.setCid(ro.getCid());
        String cPath = ro.getCpath() + "$" + ro.getCid();
        item.setCpath(cPath);
        item.setKeywords(ro.getKeywords());
        item.setWeight(ro.getWeight());
        item.setUnit(ro.getUnit());
        item.setPrice(ro.getPrice());
        item.setNum(ro.getNum());
        item.setImage(ro.getImage());
        item.setStatus(ro.getStatus().byteValue());
        item.setDescription(ro.getDescription());
        item.setCreatetime(new Date());
        item.setUpdatetime(item.getCreatetime());//为了根据此修改时间排序，所以这里要赋默认值
        item.setCreator(actionUserName);
        item.setExp(ro.getExp());
        item.setStorageconditions(ro.getStorageconditions());
        item.setIsnew(ro.getIsnew());
        item.setIsrecommend(ro.getIsrecommend());
        int result = this.itemMapper.insertSelective(item);
        if (result > 0) {
            return item.getId();
        }
        return 0L;
    }

    @Override
    public boolean updateOne(EditItemRO ro, String actionUserName) {
        Item item = new Item();
        item.setId(ro.getId());
        item.setCode(ro.getCode());
        item.setTitle(ro.getTitle());
        item.setCid(ro.getCid());
        String cpath = ro.getCpath() + "$" + ro.getCid();
        item.setCpath(cpath);
        item.setKeywords(ro.getKeywords());
        item.setWeight(ro.getWeight());
        item.setUnit(ro.getUnit());
        item.setPrice(ro.getPrice());
        item.setNum(ro.getNum());
        item.setImage(ro.getImage());
        item.setStatus(ro.getStatus().byteValue());
        item.setDescription(ro.getDescription());
        item.setUpdatetime(new Date());
        item.setUpdator(actionUserName);
        item.setExp(ro.getExp());
        item.setStorageconditions(ro.getStorageconditions());
        item.setIsnew(ro.getIsnew());
        item.setIsrecommend(ro.getIsrecommend());
        int result = this.itemMapper.updateByPrimaryKeySelective(item);
        return result > 0;
    }

    @Override
    public boolean deleteOne(Long id) {

        return this.itemMapper.deleteByPrimaryKey(id) > 0;
    }

    @Override
    public boolean deleteBatch(List<Long> ids) {
        boolean result = false;
        try {
            if (ListUtil.isNotEmpty(ids)) {
                Example example = new Example(ItemCat.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andIn("id", ids);
                result = this.itemMapper.deleteByExample(example) > 0;
            }
        } catch (Exception e) {
            this.logger.error("deleteBatch 异常", e);
        }
        return result;
    }

    @Override
    public ItemVO getOne(Long id) {

        ItemVO itemVO = null;
        Item item = this.itemMapper.selectByPrimaryKey(id);
        if (item != null) {
            itemVO = new ItemVO();
            itemVO.setId(item.getId());
            itemVO.setCid(item.getCid());
            itemVO.setCode(item.getCode());
            itemVO.setTitle(item.getTitle());
            itemVO.setKeywords(item.getKeywords());
            itemVO.setDescription(item.getDescription());
            itemVO.setWeight(item.getWeight());
            itemVO.setUnit(item.getUnit());
            itemVO.setStatus(item.getStatus());
            itemVO.setExp(item.getExp());
            itemVO.setStorageconditions(item.getStorageconditions());
            itemVO.setImage(item.getImage());

            //获取商品图片列表
            Example example = new Example(ItemPic.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("itemid", id);
            List<ItemPic> pics = this.itemPicMapper.selectByExample(example);
            if (pics != null && pics.size() > 0) {
                List<ItemPicVo> itemPicVos = new ArrayList<>();
                ItemPicVo itemPicVo;
                for (ItemPic itemPic : pics) {
                    itemPicVo = new ItemPicVo();
                    itemPicVo.setId(itemPic.getId());
                    itemPicVo.setImageurl(itemPic.getImageurl());
                    itemPicVos.add(itemPicVo);
                }
                itemVO.setItempics(itemPicVos);
            } else {
                itemVO.setItempics(new ArrayList<>());
            }
        }
        return itemVO;

    }

    @Override
    public MsgDatasVO getList(Long cid, String cpath, String id, String name, Integer pageNum, Integer pageSize, Integer isnew, Integer isrecommend) {

        MsgDatasVO result = new MsgDatasVO();
        try {
            PageHelper.startPage(pageNum, pageSize);
            Example example = new Example(Item.class);
            Example.Criteria criteria = example.createCriteria();
            //不显示已经删除的商品
            criteria.andNotEqualTo("status", ItemStatusEnum.DELETE.getCode());
            if (StringUtil.isNotEmpty(id)) {
                criteria.andEqualTo("id", id);
            }
            if (StringUtil.isNotEmpty(name)) {
                criteria.andLike("title", "%" + name + "%");
            }
            //可以当前分类及子分类的商品
//            if(cid>0) {
//                cpath+="$"+cid;
//                criteria.andLike("cpath", ""+cpath+"%");
//            }
//            if (cid > 0) {
//                criteria.andEqualTo("cid", cid);
//            }


            if (isnew != null && isnew > -1) {
                criteria.andEqualTo("isnew", isnew);
            }
            if (isrecommend != null && isrecommend > -1) {
                criteria.andEqualTo("isrecommend", isrecommend);
            }
            if (cid > 0) {
                if (StringUtil.isNotEmpty(cpath)) {
                    cpath += "$" + cid;
                } else {
                    cpath = cid.toString();
                }
                cpath += "$";

                // criteria.andLike("CONCAT(cpath,'$')", "" + cpath + "%");

                criteria.andCondition("CONCAT(cpath,'$') like '" + cpath + "%'");
            }

            List<Item> dataList = this.itemMapper.selectByExample(example);
            PageInfo pageInfo = new PageInfo(dataList);
            result.setTotal(pageInfo.getTotal());
            result.setDatas(dataList);
        } catch (Exception e) {
            this.logger.error("getList 异常", e);
        }
        return result;
    }

    @Override
    public boolean isExists(Long id, Long cid, String code, String name) {


        StringBuffer stringBuffer = new StringBuffer();
        int count = customMapper.selectCount("select count(1) from t_item" +
                "" +
                " where id<>" + id + " and cid=" + cid + " and title='" + name + "'" +
                "" +
                " or (id<>" + id + " and `code`='" + code + "')");
        return count > 0;
    }

    @Override
    public boolean updateItemStatus(Long id, Integer status) {
        Item item = new Item();
        item.setId(id);
        item.setStatus(status.byteValue());
        return this.itemMapper.updateByPrimaryKeySelective(item) > 0;
    }

    @Override
    public boolean updateItemStatusBatch(List<Long> ids, Integer status) {

        Example example = new Example(Item.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id", ids);
        Item item = new Item();
        item.setStatus(status.byteValue());
        int result = this.itemMapper.updateByExampleSelective(item, example);
        return result > 0;
    }

    @Override
    public MsgDatasVO getMiniList(Long areaId, Long cid, String name, Integer pageNum, Integer pageSize, boolean isHot
            , Integer isNew, Integer isRecommend
    ) {
        MsgDatasVO result = new MsgDatasVO();
        try {

            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("select a.id,a.title,a.keywords,a.image,a.price,itemstore.num,promitem.price promprice,promitem.num promnum from t_item a ");
            stringBuffer.append(" LEFT JOIN ");
            stringBuffer.append(" (select i.itemid,i.price,i.num from t_promotion p,t_promotion_item i where p.id=i.promid and   (NOW() BETWEEN p.starttime AND p.endtime)) promitem");
            stringBuffer.append(" ON a.id=promitem.itemid ");
            stringBuffer.append(" LEFT JOIN ");
            stringBuffer.append(" (select t.itemid,sum(t.num) num from t_item_store t  where t.areaid=" + areaId + " GROUP BY t.itemid) itemstore");
            stringBuffer.append(" ON a.id=itemstore.itemid");
            stringBuffer.append(" WHERE a.status=" + ItemStatusEnum.NORMAL.getCode()); //只显示正常上架的商品
            //条件
            if (cid != null && cid > 0) {
                //需要当前分类及其所有子类下的商品
                ItemCat itemCat = itemCatMapper.selectByPrimaryKey(cid);
                if (itemCat != null) {

                    String cpath = itemCat.getPath();
                    if (StringUtil.isNotEmpty(cpath)) {
                        cpath += "$" + itemCat.getId().toString();
                    } else {
                        cpath = itemCat.getId().toString();
                    }
                    cpath += "$";
                    stringBuffer.append(" AND CONCAT(a.cpath,'$') like '" + cpath + "%'");
                }
            }
            if (StringUtil.isNotEmpty(name)) {
                stringBuffer.append(" AND a.title like '%" + name + "%'");
            }

            if (isNew != null && isNew == 1) {
                stringBuffer.append(" AND a.isnew=1");
            }
            if (isRecommend != null && isRecommend == 1) {
                stringBuffer.append(" AND a.isrecommend=1");
            }

            //排序
            if (isHot) {
                stringBuffer.append(" Order By a.saleamount desc");
            } else {
                stringBuffer.append(" Order By a.updatetime desc");
            }
            PageHelper.startPage(pageNum, pageSize);
            List<Map<String, Object>> dataList = this.customMapper.select(stringBuffer.toString());
            PageInfo pageInfo = new PageInfo(dataList);
            result.setTotal(pageInfo.getTotal());
            result.setDatas(dataList);
        } catch (Exception e) {
            this.logger.error("getMiniList 异常", e);
        }
        return result;
    }

    @Override
    public MsgDatasVO getMiniPromList(Integer promId, String name, Integer pageNum, Integer pageSize) {

        MsgDatasVO result = new MsgDatasVO();
        try {
            PageHelper.startPage(pageNum, pageSize);
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("select  a.id,a.title,a.keywords,a.image,a.price,p.price promprice,p.num promnum");
            stringBuffer.append(" FROM ");
            stringBuffer.append(" t_promotion_item p,t_item a ");
            stringBuffer.append(" WHERE p.itemid=a.id and a.`status`=" + ItemStatusEnum.NORMAL.getCode());

            if (promId != null && promId > 0) {
                stringBuffer.append(" AND p.promid=" + promId);
            }
            if (StringUtil.isNotEmpty(name)) {
                stringBuffer.append(" AND a.title like '%" + name + "%'");
            }
            List<Map<String, Object>> dataList = this.customMapper.select(stringBuffer.toString());
            PageInfo pageInfo = new PageInfo(dataList);
            result.setTotal(pageInfo.getTotal());
            result.setDatas(dataList);
        } catch (Exception e) {
            this.logger.error("getMiniPromList 异常", e);
        }
        return result;
    }

    @Override
    public ItemDetailVO getItemDetail(Long id, Long areaId, Long memberId) {
        ItemDetailVO model = null;
        Item item = this.itemMapper.selectByPrimaryKey(id);
        if (item != null && item.getStatus() != ItemStatusEnum.DELETE.getCode().byteValue()) {
            //商品主体信息
            model = new ItemDetailVO();
            model.setId(item.getId());
            model.setTitle(item.getTitle());
            model.setCode(item.getCode());
            model.setKeywords(item.getKeywords());
            model.setDescription(item.getDescription());
            model.setExp(item.getExp());
            model.setWeight(item.getWeight());
            model.setUnit(item.getUnit());
            model.setStorageconditions(item.getStorageconditions());
            model.setPrice(item.getPrice());
            model.setImage(item.getImage());//主图

            //商品图片列表
            Example example = new Example(ItemPic.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("itemid", id);
            List<ItemPic> itemPics = this.itemPicMapper.selectByExample(example);
            if (itemPics != null && itemPics.size() > 0) {
                List<String> pics = new ArrayList<>();
                itemPics.forEach((itemPic) ->
                        pics.add(itemPic.getImageurl())
                );
                model.setItempics(pics);
            }
            //查看商品促销信息
            StringBuffer sb = new StringBuffer();
            sb.append("select i.price,i.num,p.starttime,p.endtime from t_promotion p,t_promotion_item i where p.id=i.promid and   (NOW() BETWEEN p.starttime AND p.endtime) " +
                    " and i.itemid=" + id);
            List<Map<String, Object>> promList = this.customMapper.select(sb.toString());
            if (promList != null && promList.size() > 0) {
                Map map = promList.get(0);
                //促销价格
                model.setPromprice(new BigDecimal(map.get("price").toString()));
                model.setNum(Integer.valueOf(map.get("num").toString()));
                model.setPromstarttime(map.get("starttime").toString());
                model.setPromendtime(map.get("endtime").toString());
            } else {

                //查看库存
                String sqlStore = "SELECT SUM(num) num from t_item_store where areaid=" + areaId + " and itemid=" + id;
                List<Map<String, Object>> storeList = this.customMapper.select(sqlStore);
                if (storeList != null && storeList.size() > 0) {
                    Map map = storeList.get(0);
                    if (map.get("num") != null) {
                        model.setNum(Integer.valueOf(map.get("num").toString()));
                    } else {
                        model.setNum(0);
                    }
                }
            }
            //显示已经加入到购物车的数量
            if (memberId != null && memberId > 0) {
                List<Map<String, Object>> shopcartList = this.customMapper.select("select num from t_shopcart where memberid=" + memberId + " and itemid=" + id);
                if (shopcartList != null && shopcartList.size() > 0) {
                    Map map = shopcartList.get(0);
                    if (map.get("num") != null) {
                        model.setShopcartnum(Integer.valueOf(map.get("num").toString()));
                    } else {
                        model.setShopcartnum(0);
                    }
                }
            }
        }

        return model;
    }

    @Override
    public BigDecimal getItemPrice(Long id) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("select IFNULL(promitem.newpice, a.price) price from t_item a " +
                "LEFT JOIN " +
                " (select i.price newpice,i.itemid from t_promotion p,t_promotion_item i " +
                " where p.id=i.promid and   (NOW() BETWEEN p.starttime AND p.endtime)) " +
                " promitem " +
                " on a.id=promitem.itemid " +
                " where a.id=" + id);
        List<Map<String, Object>> dataList = this.customMapper.select(stringBuffer.toString());
        if (dataList != null && dataList.size() > 0) {
            Map map = dataList.get(0);
            if (map.get("price") != null) {
                return new BigDecimal(map.get("price").toString());
            }
        }
        return BigDecimal.valueOf(0);
    }

    @Override
    public boolean updateIsNewBatch(List<Long> ids, Integer status) {
        if (ids != null && ids.size() > 0) {
            Example example = new Example(Item.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("id", ids);
            Item item = new Item();
            item.setIsnew(status);
            return this.itemMapper.updateByExampleSelective(item, example) > 0;
        }
        return false;
    }

    @Override
    public boolean updateIsRecommendBatch(List<Long> ids, Integer status) {
        if (ids != null && ids.size() > 0) {
            Example example = new Example(Item.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("id", ids);
            Item item = new Item();
            item.setIsrecommend(status);
            return this.itemMapper.updateByExampleSelective(item, example) > 0;
        }
        return false;
    }

    @Override
    public boolean cancelIsNewBatch(Long cid) {
        try {
            Example example = new Example(Item.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("cid", cid);
            Item item = new Item();
            item.setIsnew(CommonStatusEnum.DISABLED.getCode());
            return this.itemMapper.updateByExampleSelective(item, example) > 0;
        } catch (Exception e) {
            this.logger.error("getMiniPromList 异常", e);
        }
        return false;
    }

    @Override
    public boolean cancelIsRecommendBatch(Long cid) {
        try {
            Example example = new Example(Item.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("cid", cid);
            Item item = new Item();
            item.setIsrecommend(CommonStatusEnum.DISABLED.getCode());
            return this.itemMapper.updateByExampleSelective(item, example) > 0;
        } catch (Exception e) {
            this.logger.error("getMiniPromList 异常", e);
        }
        return false;
    }

    @Override
    public ItemDetailVO getShareItemDetail(Long id) {
        ItemDetailVO model = null;
        Item item = this.itemMapper.selectByPrimaryKey(id);
        if (item != null && item.getStatus() != ItemStatusEnum.DELETE.getCode().byteValue()) {
            //商品主体信息
            model = new ItemDetailVO();
            model.setId(item.getId());
            model.setTitle(item.getTitle());
            model.setPrice(item.getPrice());
            model.setImage(item.getImage());//主图
            //查看商品促销信息
            StringBuffer sb = new StringBuffer();
            sb.append("select i.price,i.num,p.starttime,p.endtime from t_promotion p,t_promotion_item i where p.id=i.promid and   (NOW() BETWEEN p.starttime AND p.endtime) " +
                    " and i.itemid=" + id);
            List<Map<String, Object>> promList = this.customMapper.select(sb.toString());
            if (promList != null && promList.size() > 0) {
                Map map = promList.get(0);
                //促销价格
                model.setPromprice(new BigDecimal(map.get("price").toString()));
            }
            else

            {
                model.setPromprice(new BigDecimal(0));
            }

        }

        return model;
    }
}
